package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    /**
     * 超时订单处理任务
     * 每分钟都查看一次有没有超时的订单
     */
    @Scheduled(cron = "0 * * * * ? ")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void overTimeOrder(){
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        List<Orders> list = orderMapper.getByStatusAndOrderTimeLt(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (list !=null && list.size() > 0){
            list.forEach(order ->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("超时未付款，自动取消");
                orderMapper.update(order);
            });
        }
    }


    /**
     * 处理“派送中”状态的订单
     * 每天1点看一下 12点之前也就是前一天有没有订单没有点击完成派送的
     */
    @Scheduled(cron = "0 0 1 * * ? ")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单:{}",LocalDateTime.now());
        List<Orders> byStatusAndOrderTimeLt = orderMapper.getByStatusAndOrderTimeLt(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now().plusHours(-1));
        if (byStatusAndOrderTimeLt != null && byStatusAndOrderTimeLt.size() > 0){
            byStatusAndOrderTimeLt.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }

    }

}
